package com.kotlin.myapplicationd.model;

import android.content.Context;
import android.content.Intent;
import android.widget.Toast;


import com.google.gson.stream.MalformedJsonException;
import com.kotlin.myapplicationd.R;
import com.kotlin.network.ErrorCode;
import com.kotlin.network.retrofit.http.ApiException;
import com.kotlin.network.retrofit.progress.ProgressCancelListener;
import com.kotlin.network.retrofit.progress.ProgressDialogHandler;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * 用于在Http请求开始时，自动显示一个ProgressDialog
 * 在Http请求结束是，关闭ProgressDialog
 * 调用者自己对请求数据进行处理
 *
 */
public abstract class ProgressSubscriber<T> extends Subscriber<T> implements
		ProgressCancelListener {

	private ProgressDialogHandler mProgressDialogHandler;

	private Context context;
	private boolean isNeedDialog;//是否需要显示
	private String tag;// 标识区分哪个请求，以便特殊处理

	public ProgressSubscriber(Context context, boolean isNeedProgressDialog) {
		this.context = context;
		this.isNeedDialog = isNeedProgressDialog;
		mProgressDialogHandler = new ProgressDialogHandler(context, this, true);
	}

	public ProgressSubscriber(Context context, boolean isNeedProgressDialog, String tag) {
		this.context = context;
		this.isNeedDialog = isNeedProgressDialog;
		mProgressDialogHandler = new ProgressDialogHandler(context, this, true);
		this.tag = tag;
	}

	private void showProgressDialog() {
		if (mProgressDialogHandler != null && isNeedDialog) {
			mProgressDialogHandler.obtainMessage(ProgressDialogHandler.SHOW_PROGRESS_DIALOG).sendToTarget();
		}
	}

	private void dismissProgressDialog() {
		if (mProgressDialogHandler != null && isNeedDialog) {
			mProgressDialogHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG).sendToTarget();
			mProgressDialogHandler = null;
		}
	}

	/**
	 * 订阅开始时调用
	 * 显示ProgressDialog
	 */
	@Override
	public void onStart() {
		showProgressDialog();
	}

	/**
	 * 完成，隐藏ProgressDialog
	 */
	@Override
	public void onCompleted() {
		dismissProgressDialog();

	}

	/**
	 * 对错误进行统一处理
	 * 隐藏ProgressDialog
	 *
	 * @param e
	 */
	@Override
	public void onError(Throwable e) {
		//TODO:发布时删除
		e.printStackTrace();


		if (e instanceof SocketTimeoutException) {
			Toast.makeText(context, context.getString(R.string.net_error), Toast.LENGTH_SHORT).show();
			//ToolAlert.toastShort("网络连接超时，请检查您的网络状态");
			error(context.getString(R.string.net_error));
		} else if (e instanceof ConnectException) {
			Toast.makeText(context, context.getString(R.string.net_error), Toast.LENGTH_SHORT).show();
			//ToolAlert.toastShort("网络连接中断，请检查您的网络状态");
			error(context.getString(R.string.net_error));
		} else if (e instanceof HttpException) {
			Toast.makeText(context, context.getString(R.string.net_error), Toast.LENGTH_SHORT).show();
			//ToolAlert.toastShort("网络异常，请稍后再试");
			error(context.getString(R.string.net_error));
		} else if (e instanceof UnknownHostException) {
			Toast.makeText(context, context.getString(R.string.net_error), Toast.LENGTH_SHORT).show();
			//ToolAlert.toastShort("网络异常，请检查您的网络状态");
			error(context.getString(R.string.net_error));

		}
		else if (e instanceof MalformedJsonException) {
			Toast.makeText(context, context.getString(R.string.net_error), Toast.LENGTH_SHORT).show();
			//ToolAlert.toastShort("网络异常，请稍后再试");
			error(context.getString(R.string.net_error));

		}
		else if (e instanceof ApiException) {
			switch (((ApiException) e).getErrorCode()) {
				case ErrorCode.TokenTimeOutError:

//						Intent mIntent = new Intent(context, LoginActivity.class);
//						//mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//						mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
//
//						context.startActivity(mIntent);
//
//						Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();





					break;



				default:
					//ToolAlert.toastShort("default"+e.getMessage());
					error(e.getMessage());
					//error("网络异常，请稍后再试");
					errorCode(e.getMessage(),((ApiException) e).getErrorCode());
					break;
			}
		} else {
			//ToolAlert.toastShort("else");
			//error(e.getMessage());
			error(context.getString(R.string.net_error));
			//errorCode(e.getMessage(),((ApiException) e).getErrorCode());
		}
		dismissProgressDialog();
	}

	/**
	 * 将onNext方法中的返回结果交给Activity或Fragment自己处理
	 *
	 * @param t 创建Subscriber时的泛型类型
	 */
	@Override
	public void onNext(T t) {
		success(t);
	}

	/**
	 * 返回网络请求正常数据
	 *
	 * @param t 创建Subscriber时的泛型类型
	 */
	public abstract void success(T t);
	/**
	 * 返回网络请求返回数据为空情况
	 *
	 */
	//public void dataIsNull() {}

	/**
	 * 网络出错或服务器出错
	 */
	public void error(String errorMsg) {
		//ToolAlert.toastShort(errorMsg);
		//Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
	}
	public void errorCode(String errorMsg,int code) {

	}
	/**
	 * 取消ProgressDialog的时候，取消对observable的订阅，同时也取消了http请求
	 */
	@Override
	public void onCancelProgress() {
		if (!this.isUnsubscribed()) {
			this.unsubscribe();
		}
	}
}